var express = require('express');
var router = express.Router();
const { login } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../model/resModel')

// 登录
router.post('/login', function(req, res, next) {
  const { username, password } = req.body;
  const result = login(username, password);
  result.then(data => {    
    if (data.username) {
      // 设置session
      req.session.username = data.username;
      req.session.realname = data.realname;
      res.json(new SuccessModel())
      return;
    }
    res.json(new ErrorModel('登录失败'))
  })
  // json()方法是express提供的方法，用于返回json格式的数据
});

router.get('/login-test', function(req, res, next) {
  if (req.session.username) {
    res.json({
        errno: 0,
        message: '登录成功'
      })
      return;
    } else {
      res.json({
        errno: -1,
        message: '未登录'
      })
    }
})

// 测试获取session
router.get('/get-session', function(req, res, next) {
  const session = req.session;
  /**
   * "session": {
        "cookie": {
            "originalMaxAge": 86400000,
            "expires": "2024-10-20T10:59:46.440Z",
            "httpOnly": true,
            "path": "/"
        }
    }
   */
  res.json({
    session
  })
})

module.exports = router;
